var GAME = require('./game');

var MAKE_ROOM_STEP = 1000;
var ROOM_PLAYER_MIN = 4;
var MAX_WAIT_TIME = 30 * 1000;

var g_tryPlayers = [];


exports.addTryPlayer = function (sock) {
    sock._sock.emit('queue', MAX_WAIT_TIME);
    sock.on('sync', function (data) {
        var player = addPlayer(sock);

        sock.on('disconnect', function () {
            var idx = g_tryPlayers.indexOf(player);
            g_tryPlayers.splice(idx, 1);
        });
    });
};

function loop() {
    var roomPlayers = getGroups();
    if (roomPlayers) {
        GAME.init4(roomPlayers);
    }

    setTimeout(loop, MAKE_ROOM_STEP);
}
loop();

function addPlayer(sock, npc) {
	var player = { sock: sock, _time: new Date() , npc:npc};
    g_tryPlayers.push(player);
    return player;
}
function getGroups() {
    var roomPlayers = g_tryPlayers.splice(0, ROOM_PLAYER_MIN);
    if (roomPlayers.length == ROOM_PLAYER_MIN) {
        return roomPlayers;
    }
    else if (roomPlayers.length > 0) {
        var now = new Date();
        var waitLong = roomPlayers.some(function (p) {
            return (now - p._time) >= MAX_WAIT_TIME;
        });
        if (waitLong) {
            return roomPlayers;
        }
        else {
            g_tryPlayers = roomPlayers;
        }
    }
}
